/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-10-12 11:19:38
 * @LastEditTime: 2022-10-24 18:43:51
 */
import { createContext, useReducer, useContext } from 'react';
import {
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_FOND_ID,
  SET_SELECT_AT_ID,
  SET_SELECTED_ITEM,
  DELETE_STANDARDIZED_ITEM,
  GET_TASK,
  ADD_INSPECTION_LIST,
  EDIT_STANDARDIZED,
  SET_ACTIVE_STANDARDIZED,
  UPDATE_STANDARDIZED_LIST,
  DETECT_EXECUTING,
  SET_DETECTION_ITEM_PROCESS
} from '../constants';
import {
  fetchDetectionListByTask,
  deleteStandardizedDetectionList,
  addInspectionTask,
  editInspectionTask,
  StartDetectionTask,
  findStandardizedDetectionById
} from '@/api/standardizedDetection/detectionTask';

import { StandardizedDetectionReducer } from '../reducers/StandardizedDetectionReducer';
import { message, Modal } from 'antd';
import { selectItemByKey } from '@/utils/list';

const initialState = {
  detectExecuting: false,
  StandardizedList: [],
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectFondId: 0,
  selectATId: 0,
  /* 选中的管理条目 */
  activeStandardized: {},
  // 选中的表格条目
  selectItems: [],
  // 数据来源
  stateList: [
    { id: 0, name: '待上传' },
    { id: 1, name: '待检测' },
    { id: 2, name: '检测中' },
    { id: 3, name: '检测通过' },
    { id: 4, name: '检测不通过' }
  ],
  detectionTypeList: [
    { id: 1, name: '条目与原文' },
    { id: 2, name: '条目' },
    { id: 3, name: '原文' },
    { id: 4, name: 'EEP格式包' },
    { id: 5, name: '光盘格式包' },
    { id: 6, name: '系统环境' }
  ]
};
const StandardizedDetectionContext = createContext();
const StandardizedDetectionProvider = (props) => {
  const [state, dispatch] = useReducer(StandardizedDetectionReducer, initialState);
  const actions = {
    /**
     * @description: 设置选中的档案类型
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },
    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的全宗ID
     */
    setSelectFondId(id) {
      dispatch({ type: SET_SELECT_FOND_ID, id });
    },

    /**
     * @description: 设置选中的档案类型ID
     */
    setSelectATId(id) {
      dispatch({ type: SET_SELECT_AT_ID, id });
    },
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 更新检测进度方法
     * @param {*} data 进度信息
     */
    setDetectionItemProcess(data) {
      const { businessId, progress, entry } = data;
      const item =
        progress === 100 && entry ? entry : selectItemByKey(businessId, state.StandardizedList);
      if (item) {
        dispatch({ type: SET_DETECTION_ITEM_PROCESS, data, item });
      }
    },

    /* 添加任务 */
    addStandardizedList(params) {
      console.log({ ...params });
      return new Promise((resolve, reject) => {
        addInspectionTask({ ...params })
          .then((res) => {
            message.success('创建成功', res);
            const { data } = res;
            dispatch({ type: ADD_INSPECTION_LIST, data });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /* 修改任务 */
    editStandardizedList(params) {
      return new Promise((resolve, reject) => {
        editInspectionTask(params)
          .then((res) => {
            const { data } = res;
            const { id } = res.data;
            dispatch({ type: EDIT_STANDARDIZED, id, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    /**
     * @description:
     * @param {*} params
     * @return {*}
     */
    getInspectionList(params) {
      return new Promise((resolve, reject) => {
        fetchDetectionListByTask(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: GET_TASK, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /* 删除选中列表 */
    deleteItem(id, title = '是否移除选中的检测任务?') {
      Modal.confirm({
        title,
        content: '是否删除检测任务？，删除后不可恢复。',
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteStandardizedDetectionList(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            message.success('移除成功');
            dispatch({ type: DELETE_STANDARDIZED_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('del item Cancel');
        }
      });
    },

    /* 设置要更新上传的文件 */
    setActiveStandardized(data) {
      dispatch({ type: SET_ACTIVE_STANDARDIZED, data });
    },

    /* 上传后更新列表 */
    updateStandardizedList(data) {
      dispatch({ type: UPDATE_STANDARDIZED_LIST, data });
    },
    /* 执行检测 */
    performDetection(data) {
      return new Promise((resolve, reject) => {
        findStandardizedDetectionById(data).then((res) => {
          const { data } = res;
          if (data.status !== 1) {
            message.success('当前不是待检测状态');
            dispatch({ type: DETECT_EXECUTING, data: false });
          } else {
            StartDetectionTask(data.id)
              .then((res) => {
                const { data } = res;
                console.log('data', data);
                dispatch({ type: DETECT_EXECUTING, data: true });
                dispatch({ type: UPDATE_STANDARDIZED_LIST, data });
                resolve(data);
              })
              .catch((err) => {
                reject(err);
              });
          }
        });
      });
    },
    setDetectExecuting(data) {
      dispatch({ type: DETECT_EXECUTING, data });
    }
  };
  const filters = {
    sourcesFilter(id) {
      return state.sourcesList.find((item) => item.id === id)?.name || '-';
    },
    stateFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    },
    detectionFilter(id) {
      return state.detectionTypeList.find((item) => item.id === id)?.name || '-';
    }
  };

  return (
    <StandardizedDetectionContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </StandardizedDetectionContext.Provider>
  );
};
export const useStandardizedDetectionContext = () => {
  return useContext(StandardizedDetectionContext);
};
export { StandardizedDetectionContext, StandardizedDetectionProvider };
